//
//  CommonListViewController.swift
//  ZNZXSuperMarket
//
//  Created by 四川中农 on 2018/7/24.
//  Copyright © 2018年 四川中农. All rights reserved.
//

import UIKit
import DZNEmptyDataSet

// 常用清单

class CommonListViewController: BaseViewController,FSSegmentTitleViewDelegate {

    @IBOutlet weak var topFilterView: UIView!
    @IBOutlet weak var tableView: UITableView!
    var pageFilterTitleView:FSSegmentTitleView!
    
    var goodsTypeArray = [GoodsTypeListModel]()
    
    var dataArray = [SiteGoodsModel]()
    
    var index = 0
    var indexPath:IndexPath?
    
    lazy var alertView : AlertContentView = {
        let view = AlertContentView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: UIScreen.ScreenHeight))
        view.backClosure = { [unowned self] in
            self.removeCommonList(indexPath: self.indexPath!, closure: { (value) in
                if value {
                    self.dataArray.remove(at: self.indexPath!.row)
                    self.tableView.deleteRows(at: [self.indexPath!], with: UITableViewRowAnimation.right)
                    self.tableView.reloadData()
                }else{
                    self.tableView.endEditing(true)
                }
            })
        }
        view.leftClosure = { [unowned self] in
            self.tableView.endEditing(true)
        }
        UIApplication.shared.keyWindow?.addSubview(view)
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.title = "常用清单"
        self.tableView.rowHeight = 110
        self.tableView.backgroundColor = UIColor.backgroundColor
        
        let header = UIView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: 10))
        header.backgroundColor = UIColor.backgroundColor
        self.tableView.tableHeaderView = header
        self.tableView.emptyDataSetDelegate = self
        self.tableView.emptyDataSetSource = self
        
        self.getGoodsTypeList()
        NotificationCenter.default.addObserver(self, selector: #selector(logined), name: NSNotification.Name(rawValue: "logined"), object: nil)
    }
    
    @objc func logined(){
        self.getGoodsTypeList()
    }
    
    // MARK:获取一级和二级分类
    func getGoodsTypeList(){
        HttpRequest.requestData(.post, URLString: Api.goodsTypeList.rawValue, parameters: nil) { (result) in
            if result["msg"] as! String == "success"{
                if let array = [GoodsTypeListModel].deserialize(from: result["data"] as? [Any]) as? [GoodsTypeListModel]{
                    self.goodsTypeArray = array
                    
                    var titleArray = [String]()
                    for model in array {
                        titleArray.append(model.name)
                    }
                    
                    if self.pageFilterTitleView == nil {
                        self.initFilterView(array: titleArray)
                    }
                    
                    
                }
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    func initFilterView(array:[String]){
        self.pageFilterTitleView = FSSegmentTitleView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: 45), titles: array, delegate: self, indicatorType: FSIndicatorTypeEqualTitle)
        self.pageFilterTitleView.itemMargin = 33
        self.pageFilterTitleView.selectIndex = 0
        self.pageFilterTitleView.titleFont = UIFont.systemFont(ofSize: 13)
        self.pageFilterTitleView.titleSelectFont = UIFont.boldSystemFont(ofSize: 13)
        self.pageFilterTitleView.titleNormalColor = UIColor.init(hexColor: "#333333")
        self.pageFilterTitleView.titleSelectColor = UIColor.init(hexColor: "#f7c201")
        self.pageFilterTitleView.indicatorColor = UIColor.init(hexColor: "f7c201")
        self.pageFilterTitleView.indicatorExtension = 5
        self.topFilterView.addSubview(self.pageFilterTitleView)
        
        self.getUserCollection(bigTypeId: self.goodsTypeArray[0].id)
    }
    
    func getUserCollection(bigTypeId:Int){
        HttpRequest.requestData(.post, URLString: Api.userCollection.rawValue, parameters: ["bigTypeId":bigTypeId]) { (result) in
            if result["msg"] as! String == "success"{
                if let array = [SiteGoodsModel].deserialize(from: result["data"] as? [Any]) as? [SiteGoodsModel] {
                    self.dataArray = array
                    self.tableView.reloadData()
                }
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    func fsSegmentTitleView(_ titleView: FSSegmentTitleView!, start startIndex: Int, end endIndex: Int) {
        self.index = endIndex
        self.getUserCollection(bigTypeId: self.goodsTypeArray[endIndex].id)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: true)
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
}

extension CommonListViewController:UITableViewDataSource,UITableViewDelegate{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CommonListTableViewCell") as! CommonListTableViewCell
        cell.reload(withModel: self.dataArray[indexPath.row])
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = self.dataArray[indexPath.row]
        if model.state != 0 {
            PKhud.showText(text: "该商品已下架~")
            return
        }
        let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "GoodsDetailViewController") as! GoodsDetailViewController
        ctrl.hidesBottomBarWhenPushed = true
        if  model.isActivity == 1{
            ctrl.type = .spare
        }else if model.isDiscount == 1 {
            ctrl.type = .discount
        }
        ctrl.goodsID = self.dataArray[indexPath.row].id
        self.navigationController?.pushViewController(ctrl, animated: true)
    }
    
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
        return .delete
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        self.indexPath = indexPath
        self.alertView.show(withTitle: "是否移除常用清单？")
    }
    
    @available(iOS 11.0, *)
    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let deleAction = UIContextualAction.init(style: .destructive, title: "") { (action, sourceView, closure:@escaping (Bool)->Void) in
            self.indexPath = indexPath
            self.alertView.show(withTitle: "是否移除常用清单？")
//            self.removeCommonList(indexPath: indexPath, closure: { [unowned self] (value) in
//                if value {
//                    self.dataArray.remove(at: indexPath.row)
//                    self.tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.fade)
//                    self.tableView.reloadData()
//                }
//                closure(value)
//            })
            closure(false)
        }
        deleAction.image = UIImage.init(named: "icon_delete_3")
        deleAction.backgroundColor = UIColor.init(hexColor: "000000")
        return UISwipeActionsConfiguration.init(actions: [deleAction])
    }
    
    func removeCommonList(indexPath:IndexPath,closure:@escaping (Bool)->()){
        HttpRequest.requestData(.post, URLString: Api.userCollectionAdd.rawValue, parameters: ["goodsId":self.dataArray[indexPath.row].id ,"bigTypeId":self.dataArray[indexPath.row].bigTypeId]) { (result) in
            if result["msg"] as! String == "success"{
                closure(true)
            }else{
                closure(false)
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
}

extension CommonListViewController:DZNEmptyDataSetSource,DZNEmptyDataSetDelegate{
    
    func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
        let str = "暂时还没有小主偏爱的东西哦~"
        let attribute = NSMutableAttributedString.init(string: str)
        attribute.addAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 14),
                                 NSAttributedStringKey.foregroundColor:UIColor.init(hexColor: "666666")], range: NSRange.init(location: 0, length: str.count))
        
        return attribute
    }
    
    func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! {
        return UIImage.init(named: "img_Defaultheadimage")
    }
    
}


























